package com.lw.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lw.company.Company;
import com.lw.company.Department;
import com.lw.company.DeptListResult;
import com.lw.service.CompanyService;
import com.lw.service.DepartmentService;
import com.lw.utils.IdWorker;
import com.lw.utils.Result;
import com.lw.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController extends BaseController{
    @Autowired
    DepartmentService departmentService;
    @Autowired
    IdWorker idWorker;
    @Autowired
    CompanyService companyService;
    /**
     * 根据id查询部门 详情
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(@RequestParam(value = "id") String id){
        Department department = departmentService.getById( id );
        return new Result( ResultCode.SUCCESS,department );
    }
    /**
     * 根据企业id查询全部部门 并查询其所属公司
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll(){
        Company company = companyService.getById( companyId );
        List<Department> list = departmentService.list(new QueryWrapper<Department>().eq( "company_id",companyId));
        DeptListResult deptListResult = new DeptListResult( company, list );
        return new Result( ResultCode.SUCCESS,deptListResult );
    }

    /**
     * 通过id删除部门
     * @param map
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestBody HashMap<String, String> map){
        departmentService.removeById( map.get( "id" ) );
        return Result.SUCCESS();
    }

    /**
     * 更新或者保存部门
     * @param department
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Department department){
        Department temp=null;
        if (department.getId()!=null){
            //更新 先查再更
//            temp=departmentService.getById( department.getId() );
//            temp.setName( department.getName() );
            temp=department;
        }else {
            //保存部门 需要给部门一个公司的id
            temp=department;
            String id=idWorker.nextId()+"";
            temp.setId( id );
            temp.setCompanyId( companyId );
        }
        departmentService.saveOrUpdate( temp );
        return Result.SUCCESS();
    }
}
